//
//  VerifyCodeInputView.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/22.
//

#import "VerifyCodeInputView.h"
#import <YYKit.h>
#import <Masonry.h>


@interface VerifyCodeInputView ()
@property (nonatomic, strong) NSMutableArray<UILabel *> *items;
@end
@implementation VerifyCodeInputView


- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _items = [NSMutableArray array];
        
        [self addSubview:self.bgView];
        [self addSubview:self.tf];
        
        [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        [self.tf mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.mas_equalTo(0);
        }];
    }
    return self;
}

- (void)setNumber:(NSInteger)number {
    _number = number;
    
    [_bgView removeAllSubviews];
    for (int i=0; i<number; i++) {
        UILabel *label = [UILabel new];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = aspectDefaultFont(24);
        [self.bgView addSubview:label];
        
        [_items addObject:label];
    }
    
    [_items mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:20 tailSpacing:20];
    [_items mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_bgView);
    }];
}

- (void)textFieldDidChanged:(UITextField *)tf {
    NSString *text = tf.text;
    if (text.length > _number) {
        text = [text substringToIndex:_number];
        tf.text = text;
    }
    
    for (int i = 0; i<_number; i++) {
        if (i < text.length) {
            self.items[i].text = [text substringWithRange:NSMakeRange(i, 1)];
        } else {
            self.items[i].text = @"";
        }
    }
    if (text.length >= _number) {
        !self.inputFullCallback ?: self.inputFullCallback(text);
    }
}

- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [UIView new];
        _bgView.backgroundColor = UIColorHex(#FFEDF5);
        _bgView.layer.cornerRadius = 15;
        @weakify(self);
        [_bgView jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @strongify(self);
            [self.tf becomeFirstResponder];
        }];
    }
    return _bgView;
}
- (UITextField *)tf {
    if (!_tf) {
        _tf = [UITextField new];
        [_tf addTarget:self action:@selector(textFieldDidChanged:) forControlEvents:UIControlEventEditingChanged];
        _tf.alpha = 0;
    }
    return _tf;
}
@end
